﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MyDeeWeibo.Classes;

namespace MyDeeWeibo.PageViews
{
    public partial class SecretTimeline : PhoneApplicationPage
    {
        #region DependencyProperties

        #region SecretTimelineListProperty
        public static readonly DependencyProperty SecretTimelineListProperty =
            DependencyProperty.Register(
            "SecretTimelineList",
            typeof(ObservableCollection<WStatus>),
            typeof(SecretTimeline),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> SecretTimelineList
        {
            get { return (ObservableCollection<WStatus>)GetValue(SecretTimelineListProperty); }
            set { SetValue(SecretTimelineListProperty, value); }
        }
        #endregion

        #region ProgressIndicatorIsVisibleProperty
        public static readonly DependencyProperty ProgressIndicatorIsVisibleProperty =
            DependencyProperty.Register("ProgressIndicatorIsVisible",
            typeof(bool),
            typeof(SecretTimeline),
            new PropertyMetadata(false));

        public bool ProgressIndicatorIsVisible
        {
            get { return (bool)GetValue(ProgressIndicatorIsVisibleProperty); }
            set { SetValue(ProgressIndicatorIsVisibleProperty, value); }
        }
        #endregion

        #endregion

        private DeeCmdBase cmdBase;
        private DeeNetEngine netEngine;
        //private WStatus[] secretStatus;
        //private int k;

        //private ScrollViewer myScrollViewer = null;

        public string refresh_since;
        public string refresh_since_save;
        public string refresh_max;
        public string refresh_max_save;
        public bool refresh_new;

        public ObservableCollection<WStatus> DataCollection { get; set; }
        public ObservableCollection<WStatus> BuildCollection()
        {
            //DataCollection = new ObservableCollection<WStatus>();
            //DataCollection.Add(secretStatus);
            SecretTimelineList = DataCollection;
            return SecretTimelineList;
        }

        public SecretTimeline()
        {
            refresh_since = "0";
            refresh_max = "0";
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.ProgressIndicator = new ProgressIndicator();
            SystemTray.ProgressIndicator.Text = "数据传输中";

            Binding bindingData;
            bindingData = new Binding("ProgressIndicatorIsVisible");
            bindingData.Source = this;
            BindingOperations.SetBinding(SystemTray.ProgressIndicator, ProgressIndicator.IsVisibleProperty, bindingData);
            BindingOperations.SetBinding(SystemTray.ProgressIndicator, ProgressIndicator.IsIndeterminateProperty, bindingData);

            RefreshTimeline();
        }

        private void RefreshTimeline()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdNormalMessages
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "50",
                sinceID = refresh_since,
                maxID = refresh_max
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.FRIENDS_TIMELINE, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        WStatuses ftimeliststatuses = null;
                        try
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(WStatuses));
                            ftimeliststatuses = ser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }

                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            int i = 0;
                            DataCollection = new ObservableCollection<WStatus>(ftimeliststatuses.statuses);
                            WStatus[] temp = DataCollection.ToArray();
                            for (int j = 0; j < temp.Length; j++)
                            {
                                if (DataCollection[i].user.following)
                                {
                                    DataCollection.RemoveAt(i);
                                }
                                else
                                {
                                    i++;
                                }
                            }
                            SecretTimelineList = DataCollection;
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void ListBox_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {

        }

        private void secretTimeline_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void toTopButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void refreshIconButton_Click(object sender, EventArgs e)
        {

        }
    }
}